use axum::{response::IntoResponse, routing::post, Extension, Json, Router};
use serde::Deserialize;
use std::sync::Arc;

use crate::{
    server::{ApiOk, AppState, CarCmd},
    Result,
};

pub fn router() -> Router {
    Router::new().route("/", post(control_car))
}

#[derive(Debug, Deserialize)]
struct PostData {
    cmd: CarCmd,
}

// 控制小车的行为
async fn control_car(
    Extension(app_state): Extension<Arc<AppState>>,
    body: String,
) -> Result<impl IntoResponse> {
    let post_data = serde_json::from_str::<PostData>(&body)?;

    let car_data = match post_data.cmd {
        CarCmd::Stop => (0.0, 0.0),
        CarCmd::Froward => (0.2, 0.0),
        CarCmd::Back => (-0.2, 0.0),
        CarCmd::Left => (0.0, 0.2),
        CarCmd::Right => (0.0, -0.2),
    };

    app_state.car_listen.send(car_data).ok();

    Ok(Json(ApiOk::OK))
}
